package com.briup.user.service.impl;

import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
//import com.briup.common.utils.SystemUtils; TODO 当前用户默认为1
import com.briup.common.utils.UserContext;
import com.briup.user.domain.po.Address;
import com.briup.user.mapper.AddressMapper;
import com.briup.user.mapper.UserMapper;
import com.briup.user.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author qinyc
* @description 针对表【es_address(收货地址表)】的数据库操作Service实现
* @createDate 2024-12-24 09:16:52
*/
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private SystemUtils systemUtils;

    @Override
    public List<Address> getAll() {
        return addressMapper.getAllByUserId(UserContext.getUser());
    }

    @Override
    public void addAddress(Address address) {
        address.setUserId(UserContext.getUser());
        address.setFlag(0);
        addressMapper.insert(address);
    }

    @Override
    public void updateAddress(Address address) {
        address.setUserId(UserContext.getUser());
        addressMapper.update(address);
    }

    @Override
    public void deleteAddress(Integer id) {
        addressMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void setDefaultAddress(Integer id) {
        //查询一下是否有默认的收货地址
        Integer count = addressMapper.selectIsHaveDefaultAddress(UserContext.getUser());
        if (count >= 1){
            throw new SystemException(CodeAndMessageEnum.DEFAULT_ADDRESS_IS_EXIST);
        }
        //设置默认的收货地址
        addressMapper.setDefaultAddress(id);
        userMapper.setDefaultAddress(id,UserContext.getUser());
    }

    @Override
    @Transactional
    public void cancelDefaultAddress(Integer id) {
        addressMapper.cancelDefaultAddress(id);
        userMapper.cancelDefaultAddress(UserContext.getUser());
    }
}




